package com.zyndev.tool.validation.core;

import com.zyndev.tool.validation.ValidResult;
import com.zyndev.tool.validation.constraints.Size;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by zhang yufei on 2017/12/9.
 */
public class SizeValid<T> implements ValidRole<T>{
    @Override
    public ValidResult execute(T t, Field field) {
        Size size = field.getAnnotation(Size.class);
        if (null != size) {
            try {
                field.setAccessible(true);
                if (null == field.get(t)) {
                    return new ValidResult(false, size.message());
                }
                String fieldTypeName = field.getType().getName();
                int fieldSize = 0;
                if ("java.lang.String".equals(fieldTypeName)) {
                    String fieldValue = (String) field.get(t);
                    fieldSize = fieldValue.length();
                } else if ("java.util.List".equals(fieldTypeName)) {
                    List fieldValue = (List) field.get(t);
                    fieldSize = fieldValue.size();
                } else if ("java.util.Map".equals(fieldTypeName)) {
                    Map fieldValue = (Map) field.get(t);
                    fieldSize = fieldValue.size();
                } else if ("java.util.Set".equals(fieldTypeName)) {
                    Set fieldValue = (Set) field.get(t);
                    fieldSize = fieldValue.size();
                }
                if (fieldSize < size.min() || fieldSize > size.max()) {
                    return new ValidResult(false, size.message());
                }
            } catch (Exception e) {
                System.out.println(e);
                return new ValidResult(false, e.getMessage());
            }
        }
        return new ValidResult(true, "");
    }
}
